package com.example.printservice.utils.impl;

import com.aspose.cells.*;
import com.aspose.pdf.devices.JpegDevice;
import com.aspose.words.*;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.example.printservice.constants.Constants;
import com.example.printservice.utils.ToImg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
public class ToImgImpl implements ToImg {
    @Override
    public String toImg(String path) {
        System.out.println(path);
        Path filePath = FileSystems.getDefault().getPath(path);
        System.out.println(filePath);
        // 文件名
        String fileName = filePath.getFileName().toString();
        // 存放处理结果的文件夹
        String dirName =Constants.RESULT_PATH + fileName.substring(0, fileName.lastIndexOf(".")) + UUID.randomUUID();
        try {
            Files.createDirectories(Paths.get(dirName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (fileName.endsWith(".pdf")) {
            dirName = pdfToImg(filePath.toString(), dirName);
        } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".txt")) {
            dirName = wordToImg(filePath.toString(), dirName);
        } else if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
            dirName = excelToImg(filePath.toString(), dirName);
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
            dirName = picToImg(filePath.toString(), dirName);
        } else {
            try {
                System.out.println(fileName);
                throw new Exception("无法解析的文件");
            } catch (Exception e) {
                log.error("无法解析的文件");
            }
        }
        return dirName;
    }

    @Override
    public String wordToImg(String filePath, String resultPath) {
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(classLoader.getResourceAsStream("license.xml"));
            long old = System.currentTimeMillis();
            Document doc = new Document(filePath);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            System.out.println(doc.getPageCount());
            for (int i = 0; i < doc.getPageCount(); i++) {
                options.setPageSet(new PageSet(i));
                doc.save(resultPath + "\\" + (i+1) + ".jpg", options);
            }
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultPath;
    }

    @Override
    public String picToImg(String filePath, String resultPath) {
        try {
            // 存放处理结果的文件夹
            Path source = Paths.get(filePath);
            Files.move(source, Paths.get(resultPath + "\\" +  "1.jpg"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return resultPath;
    }

    @Override
    public String excelToImg(String filePath, String resultPath) {
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            com.aspose.cells.License license = new com.aspose.cells.License();
            license.setLicense(classLoader.getResourceAsStream("license.xml"));
            long old = System.currentTimeMillis();
            Workbook workbook = new Workbook(filePath);
            ImageOrPrintOptions options = new ImageOrPrintOptions();
            options.setImageFormat(ImageFormat.getJpeg());
            int count = 0;
            for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
                // Get the worksheet.
                Worksheet sheet = workbook.getWorksheets().get(i);
                // Create a SheetRender object with respect to your desired sheet
                SheetRender sr = new SheetRender(sheet, options);
                for (int j = 0; j < sr.getPageCount(); j++) {
                    count++;
                    sr.toImage(j, resultPath + "\\" + count + ".jpg");
                }
            }
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public String pdfToImg(String filePath, String resultPath) {
        try {
            long old = System.currentTimeMillis();
            com.aspose.pdf.Document doc = new com.aspose.pdf.Document(filePath); //加载源文件数据
            JpegDevice jpegDevice = new JpegDevice();
            for (int i = 1; i <= doc.getPages().size(); i++) {
                File file = new File(resultPath + "/"+i+".jpg");
                FileOutputStream fileOs = new FileOutputStream(file);
                jpegDevice.process(doc.getPages().get_Item(i), fileOs);
                fileOs.close();
            }
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(resultPath);
        return resultPath;
    }
}
